package com.example.mingyue.datasource;


import com.alibaba.fastjson.JSON;
import com.example.mingyue.common.PageBean;
import com.example.mingyue.model.entity.Post;
import com.example.mingyue.model.vo.PostVO;
import com.example.mingyue.service.PostService;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 查询帖子资源的统一规范,搜索Es
 * title、tags、content
 */
@Service
public class PostDataSource implements DataSource<PostVO> {


    @Autowired
    private RestHighLevelClient client;

    @Override
    public PageBean doSearch(String searchText, Integer page, Integer pageSize) {

        try {
            SearchRequest request = new SearchRequest("post");

            if (searchText == null || "".equals(searchText)) {
                request.source().query(QueryBuilders.matchAllQuery());
            } else {
                request.source().query(QueryBuilders.matchQuery("all", searchText));
            }

            Integer pageIndex = page - 1;
            request.source().from(pageIndex).size(pageSize);

            // 4.发送请求，得到结果
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);

            PageBean<Post> Posts = getPage(response);

            return Posts;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }

    private PageBean<Post> getPage(SearchResponse response) {
        // 5.解析响应结果
        SearchHits searchHits = response.getHits();
// 5.1获取总条数
        long total = searchHits.getTotalHits().value;
// 5.2获取文档数组并且遍历
        SearchHit[] hits = searchHits.getHits();

        List<Post> posts = new ArrayList<>();
        for (SearchHit hit : hits) {
            //获取文档数据源
            String json = hit.getSourceAsString();
            //反序列化
            Post postVODoc = JSON.parseObject(json, Post.class);
            posts.add(postVODoc);
        }

        return new PageBean<>(total,posts);
    }
}
